package thread;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

/**
 * @author ZhuQi
 * @ClassName ThreadStopDemo1
 * @Date 2022/9/13 9:35
 * @Version 1.0
 * @Description 测试 volatile 变量
 */
public class ThreadStopDemo1 {

    /**
     * 演示 volatile
     *  *: System.out.println 有锁会刷新线程中变量的值。所以此处去掉也能执行。
     */
    static volatile boolean isStop = false;

    @SneakyThrows
    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (isStop) {
                    System.out.println("停止执行");
                    break;
                }
                System.out.println("继续执行");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        TimeUnit.SECONDS.sleep(3);

        new Thread(() -> {
            isStop = true;
            System.out.println("isStop:" + isStop);
        }).start();
    }
}
